<template>
  <div>
    <el-cascader
        v-model="cascaderValue"
        :options="regionList"
        @change="setValue"
        :props="propsObj"
        :show-all-levels="false"
    >
    </el-cascader>
  </div>
</template>

<script>
export default {
    name:'cascaderComp',
  props: {
    value: {
      type: Number | Array
    }
    ,
    api: {
      type: Function
    },
    change: {
      type: Function
    },
    props:{
      type: Object,
      default:{}
    }
  },
  data() {
    return {
      regionList: [],
      cascaderValue: null,
      propsObj:Object.assign({ checkStrictly: false,label:'name',children:'childList',value:'id',multiple:false},this.props)
    }
  },
  watch: {
    value(newVal) {
      if (!newVal) {
        this.cascaderValue = null
      }else{
        this.getRegionList()
      }
    },
    deep: true
  },
  methods: {
    setValue(value) {
      if(!value) return
      var midValue = null
      if (this.propsObj.multiple) {
        let list = []
        value.forEach(item => {
          list.push(item[item.length - 1])
        })
        midValue = list
      } else {
        midValue = value[value.length - 1]
      }
      this.$emit('input',midValue)
      if(this.change){
        this.change(midValue)
      }
    },
    getRegionList() {
      let  removeNullChildren = (res) =>{
        for (let item of res) {
          if (!item[this.propsObj.children] || item[this.propsObj.children].length == 0) {
            delete item[this.propsObj.children]
          } else {
            removeNullChildren(item[this.propsObj.children])
          }
        }
      }
      let getParentsById = (list, id)=> {
        for (let i in list) {
          if (list[i].id == id) {//
            //查询到就返回该数组对象的value
            return [list[i].id];
          }
          if (list[i][this.propsObj.children]) {
            let node = getParentsById(list[i][this.propsObj.children], id);
            if (node !== undefined) {
              //查询到把父节把父节点加到数组前面
              node.unshift(list[i].id);
              return node;
            }
          }
        }
      }
      let  initCascaderValue = ()=> {
        if (this.propsObj.multiple){
          let list = []
          this.value.forEach(item => {
            list.push(getParentsById(this.regionList, item))
          })
          this.cascaderValue = list
        } else {
          this.cascaderValue = getParentsById(this.regionList, this.value)
        }
      }

      if (this.regionList.length > 0) {
        initCascaderValue()
      } else {
        this.api().then(res => {
          removeNullChildren(res)
          this.regionList = res
          initCascaderValue()
        })
      }
    },
  },
  created() {
    this.getRegionList()
  }
}

</script>


<style scoped lang="scss">
.el-cascader {
  //width: 220px;
  width: auto;
}

</style>
